#include "net.hpp"
#include "dispatcher.hpp"
#include <thread>

void rpcResponse(const myrpc::BaseConnection::ptr& conn,myrpc::RpcResponse::ptr& msg)
{
    std::cout<<"收到rpc响应"<<std::endl;
    std::string body=msg->serialize();
    std::cout<<body<<std::endl;
}
void topicResponse(const myrpc::BaseConnection::ptr& conn,myrpc::TopicResponse::ptr& msg)
{
    std::cout<<"收到主题响应"<<std::endl;
    std::string body=msg->serialize();
    std::cout<<body<<std::endl;
}
int main()
{
    auto dispatcher=std::make_shared<myrpc::Dispatcher>();
    auto client=myrpc::ClientFactory::create("127.0.0.1",9090);
    //注册接收到响应对应的回调函数
    dispatcher->registerHandler<myrpc::RpcResponse>(myrpc::MType::RSP_RPC,rpcResponse);
    dispatcher->registerHandler<myrpc::TopicResponse>(myrpc::MType::RSP_TOPIC,topicResponse);

    auto message_cb=std::bind(&myrpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);

    client->setMessageCallback(message_cb);
    client->connect();
    auto rpc_req=myrpc::MessageFactory::create<myrpc::RpcRequest>();
    rpc_req->setId("1");
    rpc_req->setMType(myrpc::MType::REQ_RPC);
    rpc_req->setMethod("Add");
    Json::Value param;
    param["num1"]=1;
    param["num2"]=2;
    rpc_req->setParams(param);
    client->send(rpc_req);

    auto topic_req=myrpc::MessageFactory::create<myrpc::TopicRequest>();
    topic_req->setId("2");
    topic_req->setMType(myrpc::MType::REQ_TOPIC);
    topic_req->setTopicOptype(myrpc::TopicOptype::TOPIC_CREATE);
    topic_req->setTopicKey("news");
    client->send(topic_req);
    std::this_thread::sleep_for(std::chrono::seconds(10));
    client->shutdown();
    return 0;
}